/*
 * File:   main.c
 * Author: Piotrek
 *
 * TSK - klient
 *
 * Created on 26 marzec 2011, 16:11
 */

#include <stdio.h>
#include <stdlib.h>


//sockety pod Linux
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <netdb.h>
#include <string.h>


/*
 *
 */
#define PORT 5678

#define MAXDATASIZE 100 // maksymalna ilo´s´c dancyh, jak ˛ a mo˙zemy otrzyma´c na raz



int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr; // informacja o adresie osoby ł ˛ acz ˛ acej si˛e

    if (argc != 2) {
        fprintf(stderr,"usage: client hostname\n");
        exit(1);
    }

    if ((he=gethostbyname(argv[1])) == NULL) { // pobierz informacje o ho´scie
        perror("gethostbyname");
        exit(1);
    }

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if (sockfd == -1) {
        perror("socket");
        exit(1);
    }

their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(PORT); // short, network byte order
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8); // wyzeruj reszt˛e struktury

    char* line;
    int nbytes = 100;

    line = (char *) malloc (nbytes+1);

    int addr_len = sizeof(struct sockaddr);


    char napis[5];
    strcpy(napis,"start");

    numbytes=sendto(sockfd, napis, strlen(napis),0, (struct sockaddr*) &their_addr, sizeof(struct sockaddr));

    numbytes=recvfrom(sockfd,buf, MAXDATASIZE-1, 0, (struct sockaddr *)&their_addr, &addr_len);
    printf(buf);

    while(1)
    {

    getline(&line,&nbytes,stdin);


    if((numbytes=sendto(sockfd, line, strlen(line),0, (struct sockaddr*) &their_addr, sizeof(struct sockaddr))) == -1)
    {
        perror("Error during send data");
    }

    }



/*
    if (connect(sockfd, (struct sockaddr *)&their_addr,
        sizeof(struct sockaddr)) == -1) {
        perror("connect");
        exit(1);
    }

   /* if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
        perror("recv");
        exit(1);
    }


while(numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0))
{

buf[numbytes] = '\0';
printf("Received: %s",buf);
}

*/

close(sockfd);
return 0;
}

    //getch();


